/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package 编辑器;
 
import javax.swing.tree.DefaultMutableTreeNode; 
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


/**
 *
 * @author yanxi
 */
public class 树节点 {
    public Node n;//Node.ELEMENT_NODE
    public 树节点(Node n){
        this.n=n; 
    }
    
    @Override
    public String toString(){
        if(n.getNodeType()==Node.ELEMENT_NODE){
            NamedNodeMap map=n.getAttributes();
            String s=n.getNodeName();
            for(int i=0;i<map.getLength();i++)
                s+=" "+map.item(i).getNodeName()+"=\""+map.item(i).getNodeValue()+"\""; 
            return s; 
        }
        return null;
    }
    
    public String toXMLString(){
        String s="<"+n.getNodeName();
        if(n.hasAttributes()){  
            NamedNodeMap map=n.getAttributes();
            for(int i=0;i<map.getLength();i++){
                s+=" ";
                Node node=map.item(i); 
                s+=node.getNodeName()+"="+"\"";
                s+=node.getNodeValue()+"\""; 
            } 
        } 
        if(n.getChildNodes().getLength()<=0)
            s+="/>"; 
        else if(n.getChildNodes().getLength()==1)
            s+=">"+n.getTextContent()+"</"+n.getNodeName()+">"; 
        else{
            s+=">\n";
            NodeList list=n.getChildNodes();
            for(int i=0;i<list.getLength();i++){
                if(list.item(i).getNodeType()==Node.ELEMENT_NODE)
                    s+=new 树节点(list.item(i)).toXMLString()+"\n";
            }
            s+="</"+n.getNodeName()+">"; 
        }
        return s;
    } 
    
    public DefaultMutableTreeNode createTreeNode(){ 
        DefaultMutableTreeNode treenode=new DefaultMutableTreeNode(this); 
        if(n.getChildNodes().getLength()>1) { 
            NodeList list=n.getChildNodes();
            for(int i=0;i<list.getLength();i++){
                if(list.item(i).getNodeType()==Node.ELEMENT_NODE)//只加入元素节点为子节点
                    treenode.add(new 树节点(list.item(i)).createTreeNode());
            }
        }
        return treenode;
    } 
}
